object RectangleDivider {
  case class Rectangle(x1: Double, y1: Double, x2: Double, y2: Double) {
    override def toString: String = f"($x1%.3f, $y1%.3f) to ($x2%.3f, $y2%.3f)"
  }

  def divideRectangle(xMin: Double, yMin: Double, xMax: Double, yMax: Double, tileSize: Double): List[Rectangle] = {
    val xCount = math.ceil((xMax - xMin) / tileSize).toInt
    val yCount = math.ceil((yMax - yMin) / tileSize).toInt
    (for {
      i <- 0 until xCount
      j <- 0 until yCount
    } yield {
      if (i != xCount && j != yCount) {
        val x1 = xMin + i * tileSize
        val y1 = yMin + j * tileSize
        val x2 = math.min(x1 + tileSize, xMax)
        val y2 = math.min(y1 + tileSize, yMax)
        Rectangle(x1, y1, x2, y2)
      }
      else {
        if (i == xCount && j != yCount) {
          val x1 = xMax - tileSize
          val y1 = yMin + j * tileSize
          val x2 = xMax
          val y2 = y1 + tileSize
          Rectangle(x1, y1, x2, y2)
        }
        else if(i != xCount && j == yCount) {
          val x1 = xMin + i * tileSize
          val y1 = yMax - tileSize
          val x2 = x1 + tileSize
          val y2 = yMax
          Rectangle(x1, y1, x2, y2)
        }
        else {  // i == xCount && j == yCount
          val x1 = xMax - tileSize
          val x2 = xMax
          val y1 = yMax - tileSize
          val y2 = yMax
          Rectangle(x1, y1, x2, y2)
        }
      }
    }).toList
  }

  def main(args: Array[String]): Unit = {
    // 定义原始矩形区域
    val xMin = 100.0
    val xMax = 140.0
    val yMin = -6.365899347
    val yMax = 23.634100653

    // 定义切分的小方块大小
    val tileSize = 5.12

    // 切分矩形区域
    val tiles = divideRectangle(xMin, yMin, xMax, yMax, tileSize)

    // 输出结果
    println(s"原始矩形区域: (${xMin}, ${yMin}) to (${xMax}, ${yMax})")
    println(s"切分成 ${tiles.size} 个小矩形:")
    tiles.zipWithIndex.foreach { case (tile, index) =>
      println(f"矩形 ${index + 1}%2d: ${tile.toString}")
    }
  }
}
